#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

namespace SocketModule
{
    class Socket;
    using namespace LogModule;
    using SockPtr = std::shared_ptr<Socket>;
    
    // 基类
    // 提供一个/若干个/固定模式的socket的方法
    // 模板方法模式
    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual void SocketOrDie() = 0;
        virtual void SetSocketOpt() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual int Accepter(InetAddr* client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string* out) = 0;
        virtual int Send(std::string& in) = 0;
        virtual int Fd() = 0;
        
        // 提供一个创建ListenSocket的固定套路
        void BuildTcpSocketMethod(int port)
        {
            SocketOrDie();
            SetSocketOpt();
            BindOrDie(port);
            ListenOrDie();
        }
    };


    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = gdefaultsockfd)
            : _sockfd(sockfd)
        {
        }
        virtual ~TcpSocket() = default;
        virtual void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "create socket failed";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::DEBUG) << "create socket success " << _sockfd;
            
        }
        virtual void SetSocketOpt() override
        {
            //保证服务器在异常断开之后可以立即重启，不会有bind问题
            int opt = 1;
            int n = ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }
        virtual bool BindOrDie(int port) override
        {
            if (_sockfd == gdefaultsockfd)
                return false;

            InetAddr addr(port);
            int n = ::bind(_sockfd, addr.NetAddr(), addr.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::DEBUG) << "bind success " << _sockfd;
            return true;
        }
        virtual bool ListenOrDie() override
        {
            if (_sockfd == gdefaultsockfd)
                return false;
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "listen error";
                exit(LISTEN_ERR);
            } 
            LOG(LogLevel::DEBUG) << "listen success " << _sockfd;
            return true;
        }

      
        int Accepter(InetAddr *client) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = ::accept(_sockfd, CONV(&peer), &len);
            if (newsockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                return -1;
            }
            client->SetAddr(peer, len);
            return newsockfd;
        }
        virtual void Close() override
        {
            if(_sockfd == gdefaultsockfd)
                return;
            ::close(_sockfd);
            LOG(LogLevel::DEBUG) << "close socket " << _sockfd;
        }
        virtual int Recv(std::string* out) override
        {
            char buffer[1024 * 8];
            auto size = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if(size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }

                return size;
        }
        virtual int Send(std::string& in) override
        {
            auto size = ::send(_sockfd, in.c_str(), in.size(), 0);
            return size;
        }
        virtual int Fd() override
        {
            return _sockfd;
        }
    private:
        int _sockfd;
       
    };

    //for test
    // int main()
    // {
    //     Socket *sock = new TcpSocket();
    //     sock->BuildTcpSocket(8080);
    // }
}